﻿using System;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;

namespace RoketSolutions.SP2010.Infrostructure.Common
{
    public class EnumView<TEnum> where TEnum : struct
    {
        public static TEnum Parse(string value)
        {
            return (TEnum)Enum.Parse(typeof(TEnum), value, true);
        }

        public static TEnum Parse(object value, TEnum defaultValue)
        {
            if (value == null || value.ToString().IsNullOrEmpty())
                return defaultValue;

            TEnum result;
            return TryParse(value.ToString(), out result) ? result : defaultValue;
        }

        public static bool TryParse(string value)
        {
            try
            {
                var result = Enum.Parse(typeof(TEnum), value, true);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool TryParse(string value, out TEnum result)
        {
            if (TryParse(value))
            {
                result = Parse(value);
                return true;
            }

            result = default(TEnum);
            return false;
        }
    }
}